package cn.virens.web.components.websocket;

import java.security.Principal;
import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

public class WebSocketHandshakeHandler extends DefaultHandshakeHandler {
	@Override
	protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
		SimplePrincipal principal = new SimplePrincipal();
		principal.setName(getString(attributes, "login-name"));
		principal.setGroup(getString(attributes, "login-group"));
		principal.setAvatar(getString(attributes, "login-avatar"));
		principal.setAccount(getString(attributes, "login-account"));

		return principal;
	}

	private String getString(Map<String, Object> attributes, String string) {
		Object value = attributes.get(string);
		if (value != null) {
			return value.toString();
		} else {
			return null;
		}
	}
}
